<?php


?>
<div id="addCncForm-cont" class="hidden">
        <form class="well form-inline margin-horisontal login" action="javascript:void(0);" method="POST" name="addCncForm" id="addCncForm">
            <h2 class="errorLog hidden"></h2>
            <fieldset>
              <label for="name">Имя</label>
              <input name="name" type="text"  value=""/>
            </fieldset>
            <div class="form-actions">
              <button type="submit" class="btn btn-primary" id="addCnc-submit">
                <i class="icon-ok icon-white"></i>OK
              </button>
              <button type="reset" class="btn btn-danger" id="addCnc-cancel">
                <i class="icon-remove icon-white"></i>
                Отменить
              </button>
            </div>
        </form>
</div>

<script type="text/javascript">
  $(function() {
    var dlg       = $('#addCncForm-cont'),
        name      = dlg.find('input[name="name"]'),
        allFields = $([]).add(name);
    
    function actionLinkInit() {
      $('a[data-action]').add($('*[data-action="new"]')).click(function(event){
        dlg.children('form').data('a', $(this).parents('li').data());
        dlg.children('form').data('action', $(this).data('action'));
        dlg.dialog('open');
      });
    }
    actionLinkInit();

    dlg.dialog({
          autoOpen:   false,
          width:      350,
          modal:      true,
          draggable:  true,
          resizable:  false,
          stack:      true,
          open: function(event, ui){
            var form = $(this).children('form');
            var a = form.data('a');
            $(this).find('.errorLog').addClass('hidden');
            switch (form.data('action')) {
              case 'update':
                name.val(a.name);
                $(this).dialog('option', 'title',  'Правка:&ensp;' + a.name);
                break;

              case 'new':
                name.val('');
                $(this).dialog('option', 'title',  'Добавить');
                break;

              case 'delete':
                allFields
                  .add(form.find('fieldset'))
                  .add(form.find('.errorLog'))
                  .addClass('hidden');
                $(this).dialog('option', 'title',  'Удаление');
                $(this).find('.errorLog').removeClass('hidden').text(a.name);
                break;
            }
          },
          close: function(){
            var form = $(this).children('form');
            allFields.val('').removeClass('ui-state-error');
            allFields
              .add(form.find('fieldset'))
              .add(form.find('.errorLog'))
              .removeClass('hidden');
            $('.errorLog').addClass('hidden').empty();
          }
      }).removeClass('hidden');




    /**
     * form onReset event
     */
    dlg.find('button[type="reset"]').click(function(){
      dlg.dialog('close');
    });

    /**
     * form submit
     * @param  {[type]} e [description]
     */
    dlg.submit(function(e){
      var form = $(e.target);
      cnc_dataSubmit(form);
    });
    function cnc_dataSubmit(d){

        var action = d.data('action'),
            a      = d.data('a'),
            data   = null;

        switch (action) {
            case 'update':
                    data = {
                        action: '<?php echo ACTIONS::CONCEPTIONS_UPDATE; ?>',
                        id:     a.id,
                        name:   $('input[name="name"]').val()
                    };
              break;

            case 'new':
                data = {
                  action: '<?php echo ACTIONS::CONCEPTIONS_NEW; ?>',
                  name:   $('input[name="name"]').val()
                };
              break;

            case 'delete':
                data = {
                  action: '<?php echo ACTIONS::CONCEPTIONS_DELETE; ?>',
                  id:     a.id
                };
              break;

            default:
              var dropped  = $('li[data-id="' + Number($('#conceptions_list').data('post')) + '"]'),
                  data     = dropped.data();
              data['action']   = '<?php echo ACTIONS::CONCEPTIONS_MOVE; ?>';
              data['parent_id']   = Number( dropped.parents('.dd-item').data('id') );
              data['priority'] = dropped.index() + 1;

              data.parent_id   = (data.parent_id) ? data.parent_id : 0;

              break;
        }
        if (data) {
            jsonRequest(
              // url
              'conceptions.php',
              data,
              // onSuccess
              function(data){
                var chs = checkSession(data);
                if(!chs) {
                  Elm.loginFormModal.dialog('open');
                  return false;
                }
                cnc_dataOnsuccess(data);
              },
              // onError
              function(data){
                  console.error(data.message);
              }
            );
        }
        
    }

    function cnc_dataOnsuccess(data) {
      var response = data.response_data,
          form     = dlg.children('form');
      switch (form.data('action')) {

        case 'update':
            if (response.errorLog) {
              $('.errorLog').append($(response.errorLog));
              break;
            }
            var activeItem = $('li[data-id="'+Number(response.id)+'"]');
            activeItem.data('name', response.name);
            activeItem.children('.dd3-content').children('.dd3-name').children('a').text(response.name);

          break;

        case 'new':
            $('<li>').addClass('dd-item dd3-item').attr({
                            'data-id': response.id,
                            'data-name': response.name,
                            'data-parent_id': 0,
                            'data-state': 1
                        }).append($('<div class="dd-handle dd3-handle"> </div><div class="dd3-content"><div class="dd3-name"><a data-action="update" href="javascript:void(0);">'+response.name+'</a></div><div class="dd3-delete"><a data-action="delete" href="javascript:void(0);">Удалить</a></div></div>')).prependTo( $('.dd .dd-list'));
            actionLinkInit();
            break;

        case 'delete':
          if (response.id) {
            var dropSelector = 'li[data-id="' + parseInt(response.id) + '"]';
            $(dropSelector).hide('slow', function () {
                $(this).remove();
            });
          }
          break;

        default:
          actionLinkInit();
          break;

      }
      if (data.state) dlg.dialog('close'); else {
        $('.errorLog').empty();
        $('.errorLog').removeClass('hidden').append($(data.message));
      }
      return 0;
    }
  });
</script>
